package com.xsh.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xsh.mapper.RoleMapper;
import com.xsh.pojo.Role;
import com.xsh.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Role> findAll() {
        return roleMapper.selectAll(null);
    }

    @Override
    public List<Integer> findByUserId(Integer userId) {
        return roleMapper.selectByUserId(userId);
    }

    @Override
    public PageInfo<Role> findByPageInfo(String order, Integer limit, Integer offset) {
        PageHelper.startPage(((offset / limit) + 1), limit);
        PageInfo<Role> pageInfo = new PageInfo<>(roleMapper.selectAll(order));
        return pageInfo;
    }

    @Override
    public void addRole(Role role) {
        roleMapper.insert(role);
        for (Integer menuId : role.getMenus()) {
            roleMapper.insertRoleMenu(role.getRoleId(), menuId);
        }
    }

    @Override
    public Role findByRoleId(Integer roleId) {
        List<Integer> menus = roleMapper.selectMenuIdByRoleId(roleId);
        Role role = roleMapper.selectByRoleId(roleId);
        role.setMenus(menus);
        return role;
    }

    @Override
    public void updateRole(Role role) {
        roleMapper.update(role);
        roleMapper.deleteRoleMenuByRoleId(role.getRoleId());
        for (Integer menuId : role.getMenus()) {
            roleMapper.insertRoleMenu(role.getRoleId(), menuId);
        }
    }

    @Override
    public void deleteRole(Integer roleId) {
        roleMapper.deleteByRoleId(roleId);
    }
}
